package com.order.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

@WebServlet(name = "FileController", urlPatterns = {"/files/upload", "/files/download/*"})
@MultipartConfig
public class FileController extends HttpServlet {
    private static final String filePath = System.getProperty("user.dir") + "/files/";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查目录是否存在，不存在则创建
        File uploadDir = new File(filePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        Part filePart = request.getPart("file");  // 通过HttpServletRequest获取上传的文件部分
        String originalFilename = getSubmittedFileName(filePart);  // 获取文件的原始名称

        String realFilePath = filePath + originalFilename;
        File localFile = new File(realFilePath);

        // 如果文件已存在，重命名文件
        if (localFile.exists()) {
            originalFilename = renameFile(originalFilename);
            realFilePath = filePath + originalFilename;
            localFile = new File(realFilePath);
        }

        // 将文件写入服务器
        try (InputStream input = filePart.getInputStream()) {
            Files.copy(input, localFile.toPath());
        }

        String url = "http://localhost:8080/ordering/files/download/" + originalFilename;

        BaseController baseController = new BaseController();
        baseController.writeResultAndData(response, url);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestUri = request.getRequestURI();
        String fileName = requestUri.substring(requestUri.lastIndexOf("/") + 1);
        String realFilePath = filePath + fileName;
        File file = new File(realFilePath);

        // 如果文件不存在，返回 404 错误
        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 设置响应头，告诉浏览器下载文件
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        // 将文件写入响应输出流
        try (InputStream input = new FileInputStream(file)) {
            OutputStream output = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > 0) {
                output.write(buffer, 0, len);
            }
            output.flush();
        }
    }


    private String getSubmittedFileName(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }

    private String renameFile(String originalFilename) {
        String mainName = originalFilename.substring(0, originalFilename.lastIndexOf('.'));
        String extName = originalFilename.substring(originalFilename.lastIndexOf('.'));
        return mainName + "_" + System.currentTimeMillis() + extName;
    }
}
